package com.iye.puretennis.custom;

import android.content.Context;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.Toast;
import android.widget.ViewFlipper;
import com.iye.puretennis.R;

import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: jing wu
 * Date: 2014/12/10
 * Time: 17:24
 */
public class CustomViewFlipper extends ViewFlipper implements GestureDetector.OnGestureListener {

    private static final int FLING_MIN_DISTANCE = 100;

    private static final int FLING_MIN_VELOCITY = 100;

    int viewCount = 0;

    int currentIndex = 0; // 当前视图索引

    private int totalDataNum = 0; // 数据总数。若无数据可不设置

    private Boolean isAllowCycle = false; // 是否允许循环翻页

    private GestureDetector mGestureDetector;

    private Context mContext;
    /**
     * 加载下一页数据
     */
    private MyViewFlipperLoadData loadNextDate;

    /**
     * 加载上一页数据
     */
    private MyViewFlipperLoadData loadPreviousDate;

    public CustomViewFlipper(Context context) {
        super(context);
        mContext = context;
    }

    public CustomViewFlipper(Context arg0, AttributeSet arg1) {
        super(arg0, arg1);
        mContext = arg0;
    }

    /**
     * 初始化ViewFlipper
     *
     * @param totalNum         数据总数（数据总数确定情况下设置；默认值为0）
     * @param isAllowCycle     是否允许循环（数据总数确定情况下设置；默认值为true）
     * @param currentIndex     当前数据索引（数据总数确定情况下设置；默认值为0）
     * @param views            需要加入viewflipper的视图集合
     * @param loadPreviousData 在触发上一页操作时数据绑定
     * @param loadNextData     在触发下一页操作时数据绑定
     */
    public void setMyViewFlipper(int totalNum, Boolean isAllowCycle,
                                 int currentIndex, View[] views,
                                 MyViewFlipperLoadData loadPreviousData,
                                 MyViewFlipperLoadData loadNextData) {
        mGestureDetector = new GestureDetector(mContext, this);
        setChildTouchListener(this);
        // ViewFlipper本身来说并没有拖动事件，所以要加上这句话，不然是不会执行滑动事件的。这个问题比较畸形，找了好久。
        setLongClickable(true);
        this.totalDataNum = totalNum;
        this.isAllowCycle = isAllowCycle;
        this.currentIndex = currentIndex;
        this.loadPreviousDate = loadPreviousData;
        this.loadNextDate = loadNextData;
        this.viewCount = views.length;
        for (View view : views) {
            this.addView(view);
        }

        this.setDisplayedChild(currentIndex);
    }

    /**
     * 设置子控件监听事件
     *
     * @param view
     */
    public void setChildTouchListener(View view) {
        view.setOnTouchListener(new OnTouchListener() {

            public boolean onTouch(View v, MotionEvent event) {
                if (mGestureDetector != null) {
                    mGestureDetector.onTouchEvent(event);
                }
                return false;
            }
        });
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // 执行touch 事件
        super.onTouchEvent(event);
        return mGestureDetector.onTouchEvent(event);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event){
        //先执行滑屏事件
        mGestureDetector.onTouchEvent(event);
        super.dispatchTouchEvent(event);
        return true;
    }

    @Override
    public void showPrevious() {
        if (loadPreviousDate.canLoadData()&&(isAllowCycle || (currentIndex > 0))) {
            currentIndex--;
            loadPreviousDate.loadData(getIndex());
            this.setInAnimation(AnimationUtils.loadAnimation(this.getContext(),
                    R.anim.push_right_in));
            this.setOutAnimation(AnimationUtils.loadAnimation(
                    this.getContext(), R.anim.push_right_out));
            super.showPrevious();
        } else {
            Toast.makeText(mContext, "已经是第一页了！", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void showNext() {
        if (isAllowCycle || (currentIndex < totalDataNum - 1)) {
            currentIndex++;
            loadNextDate.loadData(getIndex());
            this.setInAnimation(AnimationUtils.loadAnimation(this.getContext(),
                    R.anim.push_left_in));
            this.setOutAnimation(AnimationUtils.loadAnimation(
                    this.getContext(), R.anim.push_left_out));
            super.showNext();
        } else {
            Toast.makeText(mContext, "已经是最后一页了！", Toast.LENGTH_SHORT).show();
        }
    }

    public int getIndex(){
        return Math.abs(currentIndex) % viewCount;
    }

    /**
     * 返回数组当前索引
     */
    public int getCurrentDataIndex() {
        if ((totalDataNum == 0)) {
            return 0;
        } else {
            return (totalDataNum + currentIndex % totalDataNum) % totalDataNum;
        }
    }

    public void setCurrentIndex(int currentIndex) {
        this.currentIndex = currentIndex;
    }

    public interface MyViewFlipperLoadData {
        /**
         * 在执行上一页或下一页时对View进行数据加载 当前view索引
         *
         * @param index 当前视图索引
         */
        void loadData(int index);

        boolean canLoadData();
    }

    public boolean onDown(MotionEvent e) {
        // TODO Auto-generated method stub
        setClickable(true);
        return true;
    }

    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                           float velocityY) {
        setClickable(false);
        if (e1.getX() - e2.getX() > FLING_MIN_DISTANCE
                && Math.abs(velocityX) > FLING_MIN_VELOCITY) {

            this.showNext();
        } else if (e2.getX() - e1.getX() > FLING_MIN_DISTANCE
                && Math.abs(velocityX) > FLING_MIN_VELOCITY) {
            this.showPrevious();
        }
        return false;
    }

    public void onLongPress(MotionEvent e) {
        // TODO Auto-generated method stub

    }

    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
                            float distanceY) {
        // TODO Auto-generated method stub
        return false;
    }

    public void onShowPress(MotionEvent e) {
        // TODO Auto-generated method stub

    }

    public boolean onSingleTapUp(MotionEvent e) {
        // TODO Auto-generated method stub
        return false;
    }


}
